<?php
namespace app\common\service;

use app\common\model\Menu as MenuModel;

class Menu{

    public function getMenus(){

        $menuModel = new MenuModel();

        $menus = $menuModel->order("id desc")->paginate(20);

        return $menus;
    }


    public function getAllMenus($ids=[]){
        $menus = MenuModel::all($ids);
        return collection($menus)->toArray();
    }

    /**
     * 获取被整理好的树
     */
    public function getMenusTree(){

        $menus = MenuModel::all();
        $menus = collection($menus)->toArray();
        $menusById = [];
        foreach($menus as $val){
            $menusById[$val['id']] = $val;
        }
        $tree = $this->findSub($menusById,0);
        return $tree;
    }

    /**
     * 生成无限级的树 应用上只要三级
     * @param $menus
     * @param $pid
     * @return array
     */
    private function findSub($menus,$pid){
        $tree = [];
        foreach($menus as $val){
            if($val['pid'] == $pid){
                $tmpVal = $val;
                $tmpPid = $val['id'];
                unset($val);
                $tmpVal['sub'] = $this->findSub($menus,$tmpPid);
                array_push($tree,$tmpVal);
            }
        }
        return $tree;
    }

    public function insert($data){

        $menuModel = new MenuModel();

        $result = $menuModel->validate('MenuValidate.add')->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$menuModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$menuModel->id];

    }


    public function update($data){
        $menuModel = new MenuModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $result = $menuModel->validate('MenuValidate.edit')->save($data,['id'=>intval($data['id'])]);

        if(false === $result){
            return ['state'=>0,'message'=>$menuModel->getError()];
        }

        return ['state'=>1,'message'=>''];
    }

    public function delete($ids){

        $menuModel = new MenuModel();

        $count = $menuModel ->destroy($ids);

        return $count;
    }
}

